package com.example.extract;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.example.common.CommonConst;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class Test {

	public static void main(String[] args) throws Exception {
		BasicCookieStore cookieStore = new BasicCookieStore();
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		String validateCode;
		try {
			Calendar calendar = Calendar.getInstance();
            int seconds = calendar.get(Calendar.SECOND);
			HttpGet httpget = new HttpGet("http://121.248.70.214/jwweb/sys/ValidateCode.aspx?t="+String.format("%s", seconds));
//			httpget.setHeader(new BasicHeader("Referer", "http://121.248.70.214/jwweb/ZNPK/TeacherKBFB.aspx"));
//			httpget.setHeader(new BasicHeader("Accept", "image/webp,image/*,*/*;q=0.8"));
//			httpget.setHeader(new BasicHeader("Accept-Encoding", "gzip, deflate, sdch"));
//			httpget.setHeader(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
//			httpget.setHeader(new BasicHeader("Connection", "keep-alive"));
//			httpget.setHeader(new BasicHeader("DNT", "1"));
//			httpget.setHeader(new BasicHeader("Host", "121.248.70.214"));
//			httpget.setHeader(new BasicHeader("User-Agent",
//					"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"));
			CloseableHttpResponse response1 = httpclient.execute(httpget);
			try {
				HttpEntity entity = response1.getEntity();
				InputStream is = entity.getContent();
				File file = new File("F:\\java_workspace\\MyClient\\validate.jpg");
				if (!file.exists())
					file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int m = 0;
				while ((m = is.read(buffer)) > -1) {
					fos.write(buffer, 0, m);
				}
				fos.flush();
				fos.close();
				is.close();
				Thread.sleep(1000);
				// httpget.releaseConnection();
				System.out.println("stored img");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				validateCode = br.readLine().trim();
				System.out.println("Login form get: " + response1.getStatusLine());
				EntityUtils.consume(entity);

				System.out.println("Initial set of cookies:");
				List<Cookie> cookies = cookieStore.getCookies();
				if (cookies.isEmpty()) {
					System.out.println("None");
				} else {
					for (int i = 0; i < cookies.size(); i++) {
						System.out.println("- " + cookies.get(i).toString());
					}
				}
			} finally {
				response1.close();
			}

			HttpPost httpPost = new HttpPost("http://121.248.70.214/jwweb/ZNPK/TeacherKBFB_rpt.aspx");
			httpPost.setHeader(new BasicHeader("Referer", "http://121.248.70.214/jwweb/ZNPK/TeacherKBFB.aspx"));
			httpPost.setHeader(new BasicHeader("Accept", "image/webp,image/*,*/*;q=0.8"));
			httpPost.setHeader(new BasicHeader("Accept-Encoding", "gzip, deflate, sdch"));
			httpPost.setHeader(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
			httpPost.setHeader(new BasicHeader("Connection", "keep-alive"));
			httpPost.setHeader(new BasicHeader("DNT", "1"));
			httpPost.setHeader(new BasicHeader("Host", "121.248.70.214"));
			httpPost.setHeader(new BasicHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"));
			// httpPost.setHeader("Referer",
			// "http://121.248.70.214/jwweb/ZNPK/TeacherKBFB.aspx");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("Sel_XNXQ", "20150"));
			params.add(new BasicNameValuePair("Sel_JS", "0000711"));
			params.add(new BasicNameValuePair("type", "1"));
			params.add(new BasicNameValuePair("txt_yzm", validateCode));
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"GB2312");
			httpPost.setEntity(formEntity);
			// http://121.248.70.214/jwweb/ZNPK/TeacherKBFB_rpt.aspx?Sel_XNXQ=20150&Sel_JS=000163&type=1&txt_yzm=57YZ
			// http://121.248.70.214/jwweb/sys/ValidateCode.aspx
			CloseableHttpResponse response2 = httpclient.execute(httpPost);
			try {
				HttpEntity entity = response2.getEntity();
				System.out.println(EntityUtils.toString(entity));
				System.out.println("Login form get: " + response2.getStatusLine());
				EntityUtils.consume(entity);

				System.out.println("Post logon cookies:");
				List<Cookie> cookies = cookieStore.getCookies();
				if (cookies.isEmpty()) {
					System.out.println("None");
				} else {
					for (int i = 0; i < cookies.size(); i++) {
						System.out.println("- " + cookies.get(i).toString());
					}
				}
			} finally {
				response2.close();
			}
		} finally {
			httpclient.close();
		}
	}

}